<template>
  <div id="app" class="container mt-5">
    <div class="card text-center" style="width: 18rem;">
      <div class="card-body">
        <h3 class="card-title">黑马自动售货机</h3>
        <button class="btn btn-success buy-button" @click="buy(5)">可乐5元</button>
        <button class="btn btn-warning buy-button" @click="buy(10)">咖啡10元</button>
        <button class="btn btn-info buy-button" @click="buy(8)">牛奶8元</button>
        <button class="btn btn-primary buy-button" @click="isRechargeDialogVisible = true">充值</button>
        <p class="card-text mt-3">银行卡余额：{{ money }}元</p>
      </div>
    </div>

    <!-- 充值对话框 -->
    <div v-if="isRechargeDialogVisible" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">充值金额</h5>
          <span class="close" @click="isRechargeDialogVisible = false">&times;</span>
        </div>
        <div class="modal-body">
          <input type="number" class="form-control" v-model="rechargeAmount" placeholder="请输入充值金额">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="isRechargeDialogVisible = false">取消</button>
          <button type="button" class="btn btn-primary" @click="recharge">确认充值</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const money = ref<number>(100)
const rechargeAmount = ref<number>(0)
const isRechargeDialogVisible = ref<boolean>(false)

const buy = (price: number) => {
  if (money.value >= price) {
    money.value -= price
  } else {
    alert('余额不足，请充值！')
  }
}

const recharge = () => {
  if (rechargeAmount.value > 0) {
    money.value += rechargeAmount.value
    rechargeAmount.value = 0 // 重置充值金额
    isRechargeDialogVisible.value = false // 隐藏充值对话框
  } else {
    alert('请输入有效的充值金额！')
  }
}
</script>

<style>
.modal {
  display: block;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

.modal-header {
  padding-bottom: 10px;
}

.modal-title {
  margin-bottom: 0;
}

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

.buy-button {
  margin: 10px 0;
  width: 100%;
}
</style>
